package com.example.demo.interceptor;

import com.example.demo.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author baekhyun
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //从配置文件中获取默认登录页的URL
    @Value("${forum-system.login.url}")
    private String defaultURL;

    /**
     * 请求的前置处理
     * true 继续请求流程 false 中断请求流程
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session并作已登录用户信息的校验
        HttpSession session= request.getSession(false);
        if (session!=null && session.getAttribute(AppConfig.USER_SESSION_KEY)!=null){
            //校验通过
            return true;
        }
        //保证跳转页面路径正确性
        if (!defaultURL.startsWith("/")){
            defaultURL="/"+defaultURL;
        }
        //校验未通过，跳转到登录页面
        response.sendRedirect(defaultURL);
        //response.setStatus(403);
        //中止请求
        return false;
    }
}
